/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ABMUsuarios.java
 *
 * Created on 16-jul-2011, 17:51:53
 */
package ventanas;

import conexiones.AdministradorDeConexiones;
import dao.PerfilesDao;
import dao.UsuariosDao;
import java.awt.Frame;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import modelo.Perfil;
import modelo.Usuario;

/**
 *
 * @author Matias Garcia
 */
public class ABMUsuarios extends javax.swing.JDialog {
    private ArrayList<Usuario> listaAuxiliar;
    private DefaultTableModel modeloUsuarios;
    private Connection conn = null;
    private Usuario usuarioLogueado = null;
    
    
      /**
     * @return the usuarioLogueado
     */
    public Usuario getUsuarioLogueado() {
        return usuarioLogueado;
    }

    /**
     * @param usuarioLogueado the usuarioLogueado to set
     */
    public void setUsuarioLogueado(Usuario usuarioLogueado) {
        this.usuarioLogueado = usuarioLogueado;
    }
    
    
    /** Creates new form ABMUsuarios */
    public ABMUsuarios(Frame parent, boolean modal){
    
    super(parent, modal);  
    this.pack();
    initComponents();
    modeloUsuarios =(DefaultTableModel) tablaUsuarios.getModel();
    centrarDatos();
    }
       
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        panelBotones = new javax.swing.JPanel();
        btnAlta = new javax.swing.JButton();
        btnConsulta = new javax.swing.JButton();
        btnModificar = new javax.swing.JButton();
        btnModificarConstrasena = new javax.swing.JButton();
        btnBaja = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        Salir = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaUsuarios = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Usuarios");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setName("frmABMUsuarios"); // NOI18N
        addWindowFocusListener(new java.awt.event.WindowFocusListener() {
            public void windowGainedFocus(java.awt.event.WindowEvent evt) {
                formWindowGainedFocus(evt);
            }
            public void windowLostFocus(java.awt.event.WindowEvent evt) {
            }
        });

        panelBotones.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        btnAlta.setText("Alta");
        btnAlta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAltaActionPerformed(evt);
            }
        });

        btnConsulta.setText("Consulta");
        btnConsulta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConsultaActionPerformed(evt);
            }
        });

        btnModificar.setText("Modificar Datos");
        btnModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnModificarActionPerformed(evt);
            }
        });

        btnModificarConstrasena.setText("Modificar Contraseña");
        btnModificarConstrasena.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnModificarConstrasenaActionPerformed(evt);
            }
        });

        btnBaja.setText("Baja");
        btnBaja.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBajaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelBotonesLayout = new javax.swing.GroupLayout(panelBotones);
        panelBotones.setLayout(panelBotonesLayout);
        panelBotonesLayout.setHorizontalGroup(
            panelBotonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBotonesLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btnAlta, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnConsulta, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnModificar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnModificarConstrasena)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnBaja, javax.swing.GroupLayout.DEFAULT_SIZE, 76, Short.MAX_VALUE)
                .addContainerGap())
        );
        panelBotonesLayout.setVerticalGroup(
            panelBotonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelBotonesLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(panelBotonesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAlta)
                    .addComponent(btnConsulta)
                    .addComponent(btnModificar)
                    .addComponent(btnModificarConstrasena)
                    .addComponent(btnBaja))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        Salir.setText("Salir");
        Salir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SalirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(204, 204, 204)
                .addComponent(Salir, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(208, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(Salir)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        tablaUsuarios.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Usuario", "Nombre", "Apellido"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tablaUsuarios.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tablaUsuarios.getTableHeader().setReorderingAllowed(false);
        jScrollPane1.setViewportView(tablaUsuarios);
        tablaUsuarios.getColumnModel().getColumn(0).setResizable(false);
        tablaUsuarios.getColumnModel().getColumn(1).setResizable(false);
        tablaUsuarios.getColumnModel().getColumn(2).setResizable(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(panelBotones, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 528, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(panelBotones, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-544)/2, (screenSize.height-415)/2, 544, 415);
    }// </editor-fold>//GEN-END:initComponents

    private void btnAltaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAltaActionPerformed
       // TODO add your handling code here:
        AltaUsuario altaUsuario = new AltaUsuario(this,true);
        altaUsuario.setVisible(true);
    }//GEN-LAST:event_btnAltaActionPerformed

    private void SalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SalirActionPerformed
        // TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_SalirActionPerformed

    private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
        // TODO add your handling code here:
      modeloUsuarios.setRowCount(0);
      listarUsuarios();  
    }//GEN-LAST:event_formWindowGainedFocus

    private void btnConsultaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConsultaActionPerformed
        // TODO add your handling code here:
      if(tablaUsuarios.getSelectedRow() != -1){   
         Usuario usuario = listaAuxiliar.get(tablaUsuarios.getSelectedRow());
            try {
                conn = AdministradorDeConexiones.obtenerConexion();
                Perfil perfil = PerfilesDao.getInstance().damePerfil(conn,usuario.getIdPerfil());
                ConsultaUsuario consultaUsuario = new ConsultaUsuario(this,true);
                consultaUsuario.mostrarUsuario(usuario,perfil);
                consultaUsuario.setVisible(true);
            } catch (Exception ex) {
                Logger.getLogger(ABMUsuarios.class.getName()).log(Level.SEVERE, null, ex);
            }      
      }
    }//GEN-LAST:event_btnConsultaActionPerformed

    private void btnModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModificarActionPerformed
        if(tablaUsuarios.getSelectedRow() != -1){   
         Usuario usuario = listaAuxiliar.get(tablaUsuarios.getSelectedRow());
            try {
                conn = AdministradorDeConexiones.obtenerConexion();
                Perfil perfil = PerfilesDao.getInstance().damePerfil(conn,usuario.getIdPerfil());
                ModificarUsuario modificarUsuario = new ModificarUsuario(this,true);
                modificarUsuario.mostrarUsuario(usuario,perfil);
                modificarUsuario.setVisible(true);
            } catch (Exception ex) {
                Logger.getLogger(ABMUsuarios.class.getName()).log(Level.SEVERE, null, ex);
            }      
      }
    }//GEN-LAST:event_btnModificarActionPerformed

    private void btnModificarConstrasenaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModificarConstrasenaActionPerformed
        if(tablaUsuarios.getSelectedRow() != -1){
            Usuario usuario = listaAuxiliar.get(tablaUsuarios.getSelectedRow());
            try {
                conn = AdministradorDeConexiones.obtenerConexion();
                ModificarContrasenaUsuario modifPass = new ModificarContrasenaUsuario(this,true);
                modifPass.mostrarUsuario(usuario);
                modifPass.setVisible(true);
            } catch (Exception ex) {
                Logger.getLogger(ABMUsuarios.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
    }//GEN-LAST:event_btnModificarConstrasenaActionPerformed

    private void btnBajaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBajaActionPerformed
        // TODO add your handling code here:
        
        if(tablaUsuarios.getSelectedRow() != -1){
            Usuario usuario = listaAuxiliar.get(tablaUsuarios.getSelectedRow());
            if(usuario.getIdUsuario() != this.getUsuarioLogueado().getIdUsuario()){
                int resultado = JOptionPane.showConfirmDialog(this, "Esta dando de baja un usuario ¿Desea Continuar?", "Advertencia", JOptionPane.YES_NO_OPTION);
                if(resultado == 0){
                    try {
                        conn = AdministradorDeConexiones.obtenerConexion();
                        UsuariosDao.getInstance().bajaDeUsuario(conn,usuario);
                        JOptionPane.showMessageDialog(this, "El nombre de usuario " + usuario.getNombreUsuario() + " fue dado de baja", "Información", JOptionPane.INFORMATION_MESSAGE);
                    }
                    catch (Exception ex) {
                        JOptionPane.showMessageDialog(this, "Error al intentar dar de baja el usuario", "Error", JOptionPane.ERROR_MESSAGE);
                    }
                }
            }
            else{
                JOptionPane.showMessageDialog(this, "Un usuario no se puede darse de baja asi mismo", "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }//GEN-LAST:event_btnBajaActionPerformed
    
    /**
     * @param args the command line arguments
     */
   
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton Salir;
    private javax.swing.JButton btnAlta;
    private javax.swing.JButton btnBaja;
    private javax.swing.JButton btnConsulta;
    private javax.swing.JButton btnModificar;
    private javax.swing.JButton btnModificarConstrasena;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel panelBotones;
    private javax.swing.JTable tablaUsuarios;
    // End of variables declaration//GEN-END:variables

 
    private void listarUsuarios(){ 
        listaAuxiliar = null;
        try {
            conn = AdministradorDeConexiones.obtenerConexion();
            //Recuperamos todos lo usuarios del sistema
            listaAuxiliar = UsuariosDao.getInstance().getAll(conn);
            cargarModeloUsuarios();
        }catch(Exception e) {e.printStackTrace();}
    }
        
    private void cargarModeloUsuarios() {
        Iterator iteraUsuario = listaAuxiliar.iterator();
            while (iteraUsuario.hasNext()) {
                String[] arregloUsuario = new String[3];
                //Obtenemos cada usuario de la lista
                Usuario usuario = (Usuario) iteraUsuario.next();
                arregloUsuario[0] = usuario.getNombreUsuario();
                arregloUsuario[1] = usuario.getNombre();
                arregloUsuario[2] = usuario.getApellido();
                //Agregamos el arreglo al modelo
                DefaultTableModel tm =(DefaultTableModel) tablaUsuarios.getModel();
                tm.addRow(arregloUsuario);
            }
    }
    
    private void centrarDatos(){
           DefaultTableCellRenderer modelocentrar = new DefaultTableCellRenderer();
           modelocentrar.setHorizontalAlignment(SwingConstants.CENTER);
           tablaUsuarios.getColumnModel().getColumn(0).setCellRenderer(modelocentrar);
           tablaUsuarios.getColumnModel().getColumn(1).setCellRenderer(modelocentrar);
           tablaUsuarios.getColumnModel().getColumn(2).setCellRenderer(modelocentrar);  
        }

  
      
}